﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// Player
/// </summary>
public class CameraPlayLogic
{
    public IViewerDrawer drawer;

    public CameraPlayLogic(IViewerDrawer iDrawer )
    {
        this.drawer = iDrawer;
    }
    /// <summary>
    /// 刷新当前逻辑信息
    /// </summary>
    public void RefrshCurrentData(int allFrameNum,string animName,List<FrameInfo> frameList,float animTolTime ,float startNormarlizeTime = 0)
    {
        ResateTickData();
        this.allFrameNum = allFrameNum;
        this.animName = animName;
        this.curFrames = frameList;
        this.animTotalTime = (int)(animTolTime * 1000);
        this.animTotTime = animTolTime;
        this.startNormarlizeTime = startNormarlizeTime;
    }

    #region  logic public Method
    public void PauseOneFrame(FrameInfo info)
    {
        if (info.FrameIndex <= allFrameNum)
        {
            //FucTempLog.LogWhite( string.Format("{0}, {1} , SelectFrameLine",info.animName,info.FrameIndex));
            curFrameIndex = info.FrameIndex;
            //先暂停
            PlayStatePause();
            RefreshOneFrame(curFrames[curFrameIndex - 1], 0);
        }
        else
        {
            FucTempLog.LogError("选择帧 不在帧范围内 !");
        }
    }

    public void PlayForward()
    {
        if (curFrameIndex < (allFrameNum - 1))
        {
            //先暂停
            if (playState == true)
            {
                PlayStatePause();
            }
            else
            {
                RefreshOneFrame(curFrames[++curFrameIndex], 0);
            }
            EventManager.TriggerEvent<FrameInfo>(CommonEvent.PlayingUpdateFrameLine, curFrames[curFrameIndex]);
        }
    }
    public void PlayReverse()
    {
        if (curFrameIndex > 0)
        {
            //先暂停
            if (playState == true)
            {
                PlayStatePause();
            }
            else
            {
                RefreshOneFrame(curFrames[--curFrameIndex], 0);
            }
            EventManager.TriggerEvent<FrameInfo>(CommonEvent.PlayingUpdateFrameLine, curFrames[curFrameIndex]);
        }
    }

    /// <summary>
    /// 播放或暂停
    /// </summary>
    public void Play()
    {
        Pause = !Pause;
        if (Pause == true)//暂停
        {
            playState = false;
            if (curFrameIndex <= 0)
            {
                curFrameIndex = 1;
            }
            drawer.PlayCrossFade(curFrames[curFrameIndex - 1], curFrameIndex, 0);
        }
        else //开始
        {
            playState = true;
        }
    }

    public void ChangeSpeed(float value)
    {
        speed = value;
    }

    public void ChangLoopModule(bool value)
    {
        this.isLoop = value;
    }

    private void RefreshOneFrame(FrameInfo info, float speed)
    {
        drawer.RefreshFrameText(info, curFrameIndex,allFrameNum);
        drawer.RefreshAnimator(info, curFrameIndex, speed);
        drawer.RefresFrameEvent(info, curFrameIndex);
        drawer.RefreshIntterrupt(info, curFrameIndex);
        drawer.RefreshAttackDef(info, curFrameIndex);
    }
    #endregion

    #region runLogic
    private bool playState = false;
    private bool isLoop = false;
    private float mTotalTime = 0.0f;

    private int curFrameIndex;

    private int allFrameNum;
    private string animName = string.Empty;
    private List<FrameInfo> curFrames;
    private int animTotalTime = 0;
    private float animTotTime = 0;
    private float startNormarlizeTime = 0;

    private int actionTime = 0;

    int mActionKey = -1;
    float mAnimSpeed = 1.0f;

    private bool m_Pause = true;
    private bool Pause
    {
        get { return m_Pause;  }
        set
        {
            m_Pause = value;
            //TODO UI Drawer
        }
    }
    private float speed = 1;

    /// <summary>
    /// 重置状态
    /// </summary>
    private void ResateTickData()
    {
        //PS ： 速度不重置
        //speed = 1;
        mAnimSpeed = 1.0f;
        mActionKey = -1;
        actionTime = 0;
        curFrameIndex = 0;
        mTotalTime = 0;
        isLoop = false;
        playState = false;
    }
    //处理动画播放
    public void Update()
    {
        var deltaTime = Time.deltaTime;
        deltaTime *= speed;

        if (playState)
        {
            int preTime = (int)(mTotalTime * 1000.0f); //上一帧 用的时间
            mTotalTime += deltaTime;
            int curTime = (int)(mTotalTime * 1000.0f);

            var delta = curTime - preTime;

            //check play start
            if (actionTime <= 0)
            {
                //Start  //[0 - 100]
                drawer.PlayAnim(animName, 0, startNormarlizeTime);
                drawer.SetAnimSpeed(mAnimSpeed);
            }
            mAnimSpeed = speed * (100 - 0) * animTotTime * 10f / animTotalTime;
            // animator.speed = mAnimSpeed;
            drawer.SetAnimSpeed(mAnimSpeed);

            //check play end
            int nextActionTime = 0;
            bool actionIsFinish = false;
            if ((actionTime + delta) > animTotalTime)
            {
                nextActionTime = delta;

                delta = animTotalTime - actionTime;
                nextActionTime -= delta;

                actionIsFinish = true;
            }

            //normalizedKey
            int nextActionKey = GetNextKey(delta);

            if (nextActionKey > mActionKey) //处理Evet //Attack //interrupt
            {
                CheckHasFrame(nextActionKey);
            }

            //TODO move
            actionTime += delta;
            mActionKey = nextActionKey;

            if (actionIsFinish)
            {
                if (isLoop)
                {
                    ResetAndPlay();
                }
                else
                {
                    ResetAndPause();
                    //播完退回stand
                    drawer.PlayCrossFade("stand", mAnimSpeed);
                }
            }
        }
    }

    /// <summary>
    /// 重置并继续播放
    /// </summary>
    private void ResetAndPlay()
    {
        Pause = false;
        playState = true;
        ResateTickData();
    }
    /// <summary>
    /// 重置并暂停
    /// </summary>
    private void ResetAndPause()
    {
        Pause = true;
        playState = false;
        //停止
        ResateTickData();
    }
    private void PlayStatePause()
    {
        Pause = true;
        playState = false;
    }

    /// <summary>
    /// normalizedTime [0-100]
    /// </summary>
    /// <param name="deltaTime"></param>
    /// <returns></returns>
    private int GetNextKey(int deltaTime)
    {
        //if (mActiveAction == null) return -1;

        int currentTime = actionTime + deltaTime; //当前执行过的时间

        // [0-100]
        if (currentTime <= animTotalTime) //在动画播放的时间内
            return currentTime * 100 / animTotalTime;

        return 100;
        // [200-...]
        //if (currentTime >= mActiveAction.TotalTime)
        //    return 200;

        // [101-199]
        //int leftTime = currentTime - mActiveAction.AnimTime;  // 融合时间
        //return 100 + leftTime * 100 / mActiveAction.PoseTime;
    }
    /// <summary>
    /// 画一帧数据
    /// </summary>
    /// <param name="normalizedKey"></param>
    private void CheckHasFrame(int normalizedKey)
    {
        for (int i = curFrameIndex; i < curFrames.Count; i++)
        {
            if (normalizedKey >= curFrames[i].NormalizedPercent)
            {
                curFrameIndex = curFrames[i].FrameIndex;
            }
        }
        curFrameIndex = curFrameIndex <= 0 ? 1 : curFrameIndex;
        var info = curFrames[curFrameIndex - 1];
        drawer.RefreshFrameText(info, curFrameIndex,allFrameNum);
        drawer.RefresFrameEvent(info, curFrameIndex);
        drawer.RefreshAttackDef(info, curFrameIndex);
        drawer.RefreshIntterrupt(info, curFrameIndex);
        drawer.RefreshSelfBox();
        EventManager.TriggerEvent<FrameInfo>(CommonEvent.PlayingUpdateFrameLine, info);
    }
    #endregion
}
